<template>
  <!-- 弹出层 -->
  <el-dialog v-model="dialogVisible" :title="isCreate ? '添加角色' : '编辑角色'" width="50%" :before-close="closeRoleAdd">
    <!-- 内容部分 -->
    <div class="userDialog_Form">
      <el-form size="small" :model="roleForm" ref="roleFormRef" label-width="120px" :rules="roleFormRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <!-- 底部按钮部分 这是一个具名插槽-->
    <template #footer>
      <div>
        <el-button type="success" size="small" @click="submitRoleAdd">提交</el-button>
        <el-button type="default" size="small" @click="closeRoleAdd">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, toRefs, watch } from "vue";
import { addRole, putRoleInfo } from "network/role.js";
let props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  isCreate: {
    type: Boolean,
    default: false, //false  是修改  true是创建
  },
  role: {
    type: Object,
    default() {
      //修改的时候穿进来的对象  复杂类型要用这种方式定义
      return {};
    },
  },
});
let emits = defineEmits(["closeRoleAdd", "refreshRoleList"]);
const { proxy } = getCurrentInstance();
let dialogVisible = ref(false);
let isCreate = ref(false);

const roleFormRef = ref(null);
const roleForm = ref({
  roleName: "",
  roleDesc: "",
});

const roleFormRules = reactive({
  roleName: [
    {
      required: true,
      message: "请输入角色名称",
      trigger: "blur",
    },
  ],
});

watch(
  props,
  (newValue, oldValue) => {
    dialogVisible.value = newValue.visible;
    isCreate.value = props.isCreate;
    roleForm.value = props.role;
  },
  { immediate: true }
);
//关闭对话框
const closeRoleAdd = () => {
  roleFormRef.value.resetFields();
  emits("closeRoleAdd");
};
//添加/更新角色
const submitRoleAdd = () => {
  roleFormRef.value.validate(async (valid) => {
    if (valid) {
      let res = ref([]);
      // console.log(roleForm.value);
      if (isCreate.value) res = await addRole(roleForm.value);
      else res = await putRoleInfo(roleForm.value);
      if (!res.success) return proxy.$notify.error({ message: res.msg, showClose: true });
      proxy.$notify.success({ message: res.msg, showClose: true });
      emits("refreshRoleList");
      closeRoleAdd();
    }
  });
};
</script>

<style lang="less" scoped></style>
